<?php

namespace App\Jobs;

use App\Models\User;
use App\Models\ProgramImage;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use OpenAI;
use Rainsens\Dinglog\Facades\Dinglog;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class TranslateNewsJob implements ShouldQueue
{
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
	
	public $model;

	public $timeout = 400;

	public function __construct($model)
	{
		$this->model = $model;
	}
	
	 public function handle()
    {

    	$model = $this->model;

    	$table = $model->getTableName();
	    /**
	     * @var $model User
	     */
    	

	    $yourApiKey = getenv('CHATGPT_API_KEY');
	   
		//$client = OpenAI::client($yourApiKey);

		$data = [];
		

		if($model->title_cn){

			$data['title_zn'] = $this->useGptTranslate($model->title_cn,3); 

			
		}


		if($model->content_cn){

			$strlen = strlen($model->content_cn);

			/*if($strlen < 5000) {
				
				$data['content_zn'] = $this->useGptTranslate($model->content_cn,1);
			}else{*/

				$pattern = "/<p.*?>(.*?)<\/p>/is"; // 正则表达式，用于匹配P标签及其内容
				 
				// 使用preg_split进行拆分
				$parts = preg_split($pattern, $model->content_cn, -1, PREG_SPLIT_DELIM_CAPTURE);
				
				$res = [];
				$i = 0;
				foreach($parts as $k=>$v){


					if(strstr($v,"作者") || strstr($v,"出品") || strstr($v,"编辑") || strstr($v,"头图") || strstr($v,"文章标题")
						|| strstr($v,"文章链接") || strstr($v,"虎嗅") || strstr($v,"36氪") || strstr($v,"微信公众号")  || strstr($v,"IT时报") ){

						continue;

					}
					if($k == 0){
						$res[$i] = $v;

					}else{

						if(strlen($res[$i]) < 5000){
							$res[$i] = $res[$i]."<p>".$v."</p>";

						}else{
							$i++;
							$res[$i] = "<p>".$v."</p>";

						}


					}


				
				}

				

				$data['content_zn'] = "";

				//$data['content_zn'] .=$this->useGptTranslate($res[10],1);

			
				foreach($res as $k=>$v){

					$data['content_zn'] .=$this->useGptTranslate($v,1);

				}

			//}
			
		}
		

		/*if($model->source == 'scmp'){

			$data['brief_zn'] = $this->briefCreate($model->title_zn,$model->content_zn,$model->source);
			$data['brief'] = "";
			$data['content_zn'] = $model->content_zn;
		}else{*/

			 $brief = $this->briefCreate($model->title_cn,$model->content_cn,$model->source);

			 $data['brief']  = $brief['brief'];



		//}

		if($data['brief']){

			$data['brief_zn'] = $this->useGptTranslate($data['brief'],2);
		}


		if($brief['keywords']){

			//$keywords = $this->getKeywords(implode(",",$brief['keywords']));
			
			$keywordArr = array_slice($brief['keywords'], 0, 5); ;

			$keywords = implode(",",$keywordArr); 

			foreach($keywordArr as $k=>$v){
				
				$this->insertImage($model->id,$v);
				sleep(1);
			}
			$imageKeyword = $keywordArr[0];

			//$data['images'] = ProgramImage::query()->where("deep_new_id",$model->id)->where("keyword",$imageKeyword)->first()->url;
			$data['keywords'] = $keywords;

			/*$imgUrl = "https://unsplash.com/napi/search/photos?page=1&per_page=20&query=".$imageKeyword;

			//https://my.visme.co/ajax/imageSearch/1506607218/AI/1?color&orientation
			
			
			$response = Http::get('https://unsplash.com/napi/search/photos', [
			    'page' => '1',
			    'per_page' => '20',
			    'query' => $imageKeyword,
			    "xp"=>'free-semantic-perf:experiment'
			]);
			if ($response->successful()) {
			    $dds = $response->json();

			    $rand = rand(0,count($dds['results']));
			   	$images= $dds['results'][$rand]['urls']['regular'];

			   	$imageContent = file_get_contents($images);
					$newFileName = "/images/".Str::random(40) . '.jpg'; // 假设是JPG格式
				Storage::disk('oss')->put($newFileName, $imageContent);
				 
				// 你现在可以通过存储的路径访问图片
				$data['images'] = Storage::disk('oss')->path($newFileName);

				$data['keywords'] = $keywords;

			} else {
			    // 错误处理
			}*/
		}
    	

    	if($model->content_cn){

			$data['content_cn'] = str_replace("_src", "src", $model->content_cn); 
		}

		if($data['content_zn']){

			$data['content_zn'] = str_replace("_src", "src", $data['content_zn']); 
		}

		//$data['is_examine']=1;
		$model->update($data);
	  
    	
    	
	    //return $this->response()->success('新闻翻译完成')->refresh();
    }

    public function getKeywords($text){
    	$content = [
		    'model' => 'gpt-3.5-turbo',
		    'messages' => [
		    	['role' => 'system', "content"=> "请根据文案提取关键词,返回最适合营销的5个关键词,返回英文内容"],
		        ['role' => 'user', 'content' => $text],
		    ]
		];

		

		$content = $this->curl($content);

	    $content = json_decode($content,true);

	    return $content['choices'][0]['message']['content'];

    }

    public function useGptTranslate($text,$source){

    	

    	if($source == 1){
    		$content = [
			    'model' => 'gpt-3.5-turbo',
			    'messages' => [
			    	['role' => 'system', "content"=> "你是个翻译工作者,将下方内容翻译成英文,保留html标签,去除作者来源"],
			        ['role' => 'user', 'content' => $text],
			    ]
			];
			$content = $this->curl($content);

	
			

			$content = json_decode($content,true);


			$noHtmlContent = strip_tags($content['choices'][0]['message']['content']);
			

			if($this->hasChinese($content['choices'][0]['message']['content'])){

				$contentEn = $content['choices'][0]['message']['content'];
				$contentEn = trim($contentEn, '"');

				return $contentEn;
				//dd($content['choices'][0]['message']['content']);
				//return $this->useGptTranslate($text,$source);
			}elseif(empty($noHtmlContent)){
				return '';
			}elseif((strstr($noHtmlContent,'html') && !strstr($noHtmlContent,'.html') && !strstr($noHtmlContent,'.shtml')) || strstr($noHtmlContent,'【') || strstr($noHtmlContent,'】') || strstr($noHtmlContent,'、、、') || strstr($noHtmlContent,'```')){

				return $this->useGptTranslate($text,$source);
			}elseif(!strstr($content['choices'][0]['message']['content'],'<p') &&  !strstr($content['choices'][0]['message']['content'],'<div')  && strlen($content['choices'][0]['message']['content']) > 1000 && $this->model->getTable() !="news"){
				
				return $this->useGptTranslate($text,$source); 
				
				
			}else{

				$contentEn = $content['choices'][0]['message']['content'];
				$contentEn = trim($contentEn, '"');

				return $contentEn;
			}
			

			

    	}elseif($source ==2){

    		$content = [
			   'model' => 'gpt-3.5-turbo',
			    'messages' => [
			    	['role' => 'system', "content"=> "你是个翻译工作者"],
			        ['role' => 'user', 'content' => '将内容【'.$text.'】翻译成英文,去除作者来源'],
			    ],
			];
			$content = $this->curl($content);
	
			$content = json_decode($content,true);

			$noHtmlContent = strip_tags($content['choices'][0]['message']['content']);


			if($this->hasChinese($content['choices'][0]['message']['content'])){
				
				return $this->useGptTranslate($text,$source);
			}elseif(empty($noHtmlContent)){
				return '';
			}elseif(strstr($noHtmlContent,'html') || strstr($noHtmlContent,'【') || strstr($noHtmlContent,'】') || strstr($noHtmlContent,'、、、') || strstr($noHtmlContent,'...')){

				return $this->useGptTranslate($text,$source);
			}else{

				$contentEn = $content['choices'][0]['message']['content'];
				$contentEn = trim($contentEn, '"');
				
				return $contentEn;
			}



    	}else{


    		$content = [
			   'model' => 'gpt-3.5-turbo',
			    'messages' => [
			    	['role' => 'system', "content"=> "你是个翻译工作者"],
			        ['role' => 'user', 'content' => '将标题【'.$text.'】翻译成英文,去除作者来源'],
			    ],
			];
			$content = $this->curl($content);
	
			$content = json_decode($content,true);
			$noHtmlContent = strip_tags($content['choices'][0]['message']['content']);
			
			if($this->hasChinese($content['choices'][0]['message']['content'])){
				return $this->useGptTranslate($text,$source);
			}elseif(empty($noHtmlContent)){
				return '';
			}elseif(strpos($noHtmlContent,'html') || strpos($noHtmlContent,'【') || strpos($noHtmlContent,'】') || strpos($noHtmlContent,'、、、') || strstr($noHtmlContent,'...')){
				return $this->useGptTranslate($text,$source);
			}else{

				$contentEn = $content['choices'][0]['message']['content'];
				$contentEn = trim($contentEn, '"');
				
				return $contentEn;
			}




    	}

    }

    //I am a technology analysis expert, please convert this article into a LinkedIn post . Requirement: 1. Professional and sharp analysis. 2. Add key data. 3. Present the key information of the article without unnecessary talk. 4. Control within 50 words.5.I would like to create a marketing poster for this article. Please choose a marketing title that is different from the original title, contains core data, has suspense, and is attractive.6.add tags

    public function briefCreate($title,$content,$source){


    	if($source !=  'scmp'){

    		if(strlen($content) > 15000){

    			$model = "gpt-3.5-turbo";
    		}else{

    			$model = "gpt-3.5-turbo";
    		}
			$titleContent = [
			    'model' => $model,
			     'messages' => [
			    	['role' => 'system', "content"=> cs()->news_brief_prompt."返回内容为摘要和关键词,关键词重点关注文章中描述的知名公司、知名品牌、知名产品、知名人物、社会热点词语等,关键词需要结合内容分析，比如内容是讲苹果公司的，那么关键词就应该是苹果公司而不是苹果，内容是讲理想汽车的，那么关键词就应该是理想汽车而不只是汽车,返回形式为json格式,不需要返回思考过程,字段brief代表摘要,keywords代表关键词"],
			        ['role' => 'user', 'content' => $content],

			    ],
			    
			]; 

			$titleResult = $this->curl($titleContent);
			
			$titleResult = json_decode($titleResult,true);
			
			$wt = $titleResult['choices'][0]['message']['content'];


			if(strstr($wt,"<think>")){

				$pattern = "/<think>\.*?<\/think>/s"; // 使用非贪婪匹配并确保可以匹配跨多行
				$wtres = preg_replace($pattern, '', $wt);
			}else{
				$wtres =$wt;
			}

			if(strstr($wtres,"```json")){

				$wtRes = str_replace("```json", "", $wtres);
				$wtRes = str_replace("```", "", $wtRes);
				
				$brirfResult = json_decode($wtRes,true);

			}else{

				$brirfResult = json_decode($wt,true);
			}
			

			
			$brief = $brirfResult['brief'];

			$keywords = $brirfResult['keywords'];


			if(strlen($brirfResult['brief'])>50){

				$titleContent = [
				    'model' => $model,
				    'messages' => [
				    	['role' => 'system', "content"=> "你是一个新闻工作者"],
				        ['role' => 'user', 'content' => '将标题【'.$title.'】和内容【'.$content.'】重新解读，要求简练清晰，观点明确, 将数据量化，返回内容不超过50字，不需要注明文章来源'],
				        ['role' => 'system', 'content' => $brirfResult['brief']],
				        ['role' => 'user', 'content' => '再简化一下，不超过50字'],
				    ]
				]; 

				$titleResult = $this->curl($titleContent);
			
				$titleResult = json_decode($titleResult,true);

				$brief  =$titleResult['choices'][0]['message']['content'];

			}

		}

		
		$brief = trim($brief, '"');
		$brief = str_replace("•","",$brief);
		$res = [
			'brief'=>$brief,
			'keywords'=>$keywords
		];


		return $res;
    }

    public function insertImage($id,$keyword){

    	/*$response = Http::get('https://unsplash.com/napi/search/photos', [
			    'page' => '1',
			    'per_page' => '3',
			    'query' => $keyword,
			    "xp"=>'free-semantic-perf:experiment'
			]);*/

    	/*$header=[
            "x-cb-apikey"=>"6a8e204fac2d41b3a79f224ccf542880",
            "x-cb-host"=> "www.istockphoto.com",
            "accept"=>"application/json"
        ];


        $response = Http::withHeaders($header)->get('https://api.cloudbypass.com/hk/search/2/image-film', [
                'istockcollection' => '',
                'phrase' => $keyword,
            ]);


    	$insertImage = [];*/




	/*if ($response->successful()) {
	    $dds = $response->json();

	    foreach($dds['gallery']['assets'] as $k=>$v){

	    	if($k<3){
	    		$images = $v['thumbUrl'];
		    	$imageContent = file_get_contents($images);
				$newFileName = "/images/".Str::random(40) . '.jpg'; // 假设是JPG格式
				Storage::disk('oss')->put($newFileName, $imageContent);

				$insertImage[$k]['url'] = Storage::disk('oss')->path($newFileName);
				$insertImage[$k]['keyword'] = $keyword;
				$insertImage[$k]['deep_new_id'] = $id;

	    	}
	    	
	    }

	    ProgramImage::insert($insertImage);

		

	} else {
	    // 错误处理
	}*/

	$insertImage = [];
	$response1 = Http::get('https://unsplash.com/napi/search/photos', [
			    'page' => '1',
			    'per_page' => '3',
			    'query' => $keyword,
			    "xp"=>'free-semantic-perf:experiment'
			]);

	if ($response1->successful()) {
	    $dds = $response1->json();
	    foreach($dds['results'] as $k=>$v){

	    	$images = $v['urls']['regular'];
	    	$imageContent = file_get_contents($images);
			$newFileName = "/images/".Str::random(40) . '.jpg'; // 假设是JPG格式
			Storage::disk('oss')->put($newFileName, $imageContent);

			$insertImage[$k]['url'] = Storage::disk('oss')->path($newFileName);
			$insertImage[$k]['keyword'] = $keyword;
			$insertImage[$k]['deep_new_id'] = $id;
	    }

	  

	    if($insertImage){

	    	ProgramImage::insert($insertImage);
	    }
	    

		

	} else {
	    // 错误处理
	}

    }

    public function  hasChinese($string) {

   		 return preg_match('/[\x{4e00}-\x{9fa5}]/u', $string);
	}

    public function curl($data){

		$curl = curl_init();
		$data = json_encode($data);


		curl_setopt_array($curl, array(
		   CURLOPT_URL => 'https://api.chatanywhere.tech/v1/chat/completions',
		   CURLOPT_RETURNTRANSFER => true,
		   CURLOPT_ENCODING => '',
		   CURLOPT_MAXREDIRS => 10,
		   CURLOPT_TIMEOUT => 0,
		   CURLOPT_FOLLOWLOCATION => true,
		   CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		   CURLOPT_CUSTOMREQUEST => 'POST',
		   CURLOPT_POSTFIELDS =>$data,
		   CURLOPT_HTTPHEADER => array(
		      'Authorization: Bearer '.env('CHATGPT_API_KEY'),
		      'User-Agent: Apifox/1.0.0 (https://apifox.com)',
		      'Content-Type: application/json'
		   ),
		));

	   $response = curl_exec($curl);

	   
	   return $response;
	}
}
